package com.example.elmmerchants.First_Page_Fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.elmmerchants.Order_Setting.Order_Setting_Page;
import com.example.elmmerchants.R;
import com.example.elmmerchants.Ringtone_Setting.Ringtone_Setting_Page;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.example.elmmerchants.Set_Open_Shop_Page;
import com.example.elmmerchants.Setting.Shop_Setting_Page;
import com.example.elmmerchants.Sign.Sign_Page;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Setting_Page extends Fragment {

    View root;
    TextView shop_name_text_view, is_open_or_close, user_account;
    RelativeLayout set_is_open_shop, shop_setting_button, ringtone_setting, order_setting;
    LinearLayout sign_out_button;

    String email, shop_name, open_hour, close_hour, open_day, close_hour_2, open_hour_2, user_account_name, shop_place;
    byte[] shop_pic_string = new byte[0];
    boolean is_loading_open_shop_page_data = false, is_loading_shop_page_data = false, is_finish_loading_ringtone_data = false, is_loading_order_page_data = false;
    int is_open_shop, shop_sold, can_served_start_time, can_served_end_time, is_open_book_order, is_all_day_can_book_order;
    AlertDialog dialog;
    String first_category, second_category, contact_phone_number;
    int book_almost_time, book_has_ride_get_order, new_order, auto_get_order, reminder_order, order_cancel, user_apply_refund, abnormal_distribution, how_many_volume;
    boolean is_open_vibrate = false;
    boolean is_open_auto_get_order = false;
    boolean is_upload_sign_out_data = false;
    AlertDialog dialog1;
    String android_id = "";

    public Setting_Page(String email) {
        this.email = email;
    }

    private class Open_Shop_Thread extends Thread {
        @Override
        public void run() {
            is_loading_open_shop_page_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        open_hour = set.getString("open_hour");
                        close_hour = set.getString("close_hour");
                        open_day = set.getString("open_day");
                        close_hour_2 = set.getString("close_hour2");
                        open_hour_2 = set.getString("open_hour2");
                        shop_pic_string = set.getBytes("shop_picture");
                    }

                    String sql2 = "SELECT * FROM merchant_book_order_setting WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql2);
                    preparedStatement.setString(1, email);
                    ResultSet set2 = preparedStatement.executeQuery();
                    while (set2.next()) {
                        can_served_start_time = set2.getInt("can_served_start_time");
                        can_served_end_time = set2.getInt("can_served_end_time");
                        is_open_book_order = set2.getInt("is_open_book_order");
                        is_all_day_can_book_order = set2.getInt("is_all_day_can_book_order");
                    }
                    is_loading_open_shop_page_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_open_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(root.getContext(), Set_Open_Shop_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("is_open_shop", is_open_shop);
                    intent.putExtra("open_hour", open_hour);
                    intent.putExtra("close_hour", close_hour);
                    intent.putExtra("can_served_start_time", can_served_start_time);
                    intent.putExtra("can_served_end_time", can_served_end_time);
                    intent.putExtra("is_open_book_order", is_open_book_order);
                    intent.putExtra("is_all_day_can_book_order", is_all_day_can_book_order);
                    intent.putExtra("open_day", open_day);
                    intent.putExtra("close_hour_2", close_hour_2);
                    intent.putExtra("open_hour_2", open_hour_2);
                    intent.putExtra("shop_name", shop_name);
                    startActivityForResult(intent, 1);
                }
            });
        }
    }

    private class Shop_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_shop_page_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        shop_name = set.getString("shop_name");
                        is_open_shop = set.getInt("is_open");
                        user_account_name = set.getString("user_name");
                        is_loading_shop_page_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (isVisible()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        shop_name_text_view.setText(shop_name);
                        user_account.setText(user_account_name);
                        if (is_open_shop == 1) {
                            is_open_or_close.setText("营业中");
                        }
                        else {
                            is_open_or_close.setText("休息中");
                        }

                        onStop();
                    }
                });
            }
            else {
                onStop();
            }
        }
    }

    private class Shop_Setting_Thread extends Thread {
        @Override
        public void run() {
            is_loading_open_shop_page_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        open_hour = set.getString("open_hour");
                        close_hour = set.getString("close_hour");
                        open_day = set.getString("open_day");
                        close_hour_2 = set.getString("close_hour2");
                        open_hour_2 = set.getString("open_hour2");
                        shop_pic_string = set.getBytes("shop_picture");
                        first_category = set.getString("first_category");
                        second_category = set.getString("second_category");
                        contact_phone_number = set.getString("contact_phone_number");
                    }

                    String sql2 = "SELECT * FROM merchant_food_business_licence WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql2);
                    preparedStatement.setString(1, email);
                    ResultSet set2 = preparedStatement.executeQuery();
                    while (set2.next()) {
                        shop_place = set2.getString("business_place");
                    }
                    is_loading_open_shop_page_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_open_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(root.getContext(), Shop_Setting_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("shop_name", shop_name);
                    intent.putExtra("first_category", first_category);
                    intent.putExtra("second_category", second_category);
                    intent.putExtra("is_open_shop", is_open_shop);
                    intent.putExtra("contact_phone_number", contact_phone_number);
                    intent.putExtra("open_hour", open_hour);
                    intent.putExtra("close_hour", close_hour);
                    intent.putExtra("open_hour_2", open_hour_2);
                    intent.putExtra("close_hour_2", close_hour_2);
                    intent.putExtra("shop_place", shop_place);
                    startActivityForResult(intent, 1);
                }
            });
        }
    }

    private class Loading_Ringtone_Data_Thread extends Thread {
        @Override
        public void run() {
            is_finish_loading_ringtone_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant_ringtone_setting WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        book_almost_time = set.getInt("book_almost_time");
                        book_has_ride_get_order = set.getInt("book_has_ride_get_order");
                        new_order = set.getInt("new_order");
                        auto_get_order = set.getInt("auto_order");
                        reminder_order = set.getInt("reminder_order");
                        order_cancel = set.getInt("order_cancel");
                        user_apply_refund = set.getInt("user_apply_refund");
                        abnormal_distribution = set.getInt("abnormal_distribution");
                        how_many_volume = set.getInt("volume");
                        if (set.getInt("is_open_vibrate") == 1) {
                            is_open_vibrate = true;
                        }
                        else {
                            is_open_vibrate = false;
                        }
                        is_finish_loading_ringtone_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_loading_ringtone_data) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(root.getContext(), Ringtone_Setting_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("book_almost_time", book_almost_time);
                    intent.putExtra("book_has_ride_get_order", book_has_ride_get_order);
                    intent.putExtra("new_order", new_order);
                    intent.putExtra("auto_get_order", auto_get_order);
                    intent.putExtra("reminder_order", reminder_order);
                    intent.putExtra("order_cancel", order_cancel);
                    intent.putExtra("user_apply_refund", user_apply_refund);
                    intent.putExtra("abnormal_distribution", abnormal_distribution);
                    intent.putExtra("how_many_volume", how_many_volume);
                    intent.putExtra("is_open_vibrate", is_open_vibrate);
                    startActivity(intent);
                }
            });
        }
    }

    private class Loading_Order_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_order_page_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getInt("is_open_auto") == 1) {
                            is_open_auto_get_order = true;
                        }
                        else {
                            is_open_auto_get_order = false;
                        }
                        is_loading_order_page_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_order_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(root.getContext(), Order_Setting_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("is_open_auto_get_order", is_open_auto_get_order);
                    startActivity(intent);
                }
            });
        }
    }

    private class Upload_Sign_Out_Data_Thread extends Thread {
        @Override
        public void run() {
            is_upload_sign_out_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `elm`.`merchant` set phone_id = ? WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, "");
                    preparedStatement.setString(2, email);
                    preparedStatement.executeUpdate();
                    is_upload_sign_out_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_upload_sign_out_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    android_id = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
                    dialog.dismiss();

                    Intent intent = new Intent(root.getContext(), Sign_Page.class);
                    intent.putExtra("android_id", android_id);
                    startActivity(intent);
                    getActivity().finish();
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_setting__page, container, false);

        shop_name_text_view = root.findViewById(R.id.shop_name);
        is_open_or_close = root.findViewById(R.id.is_open_or_close);
        user_account = root.findViewById(R.id.user_account);
        set_is_open_shop = root.findViewById(R.id.set_is_open_shop);
        shop_setting_button = root.findViewById(R.id.shop_setting_button);
        ringtone_setting = root.findViewById(R.id.ringtone_setting);
        order_setting = root.findViewById(R.id.order_setting);
        sign_out_button = root.findViewById(R.id.sign_out_button);

        Shop_Data_Thread shopDataThread = new Shop_Data_Thread();
        shopDataThread.start();

        set_is_open_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Open_Shop_Thread openShopThread = new Open_Shop_Thread();
                openShopThread.start();
            }
        });

        shop_setting_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Shop_Setting_Thread shopSettingThread = new Shop_Setting_Thread();
                shopSettingThread.start();
            }
        });

        ringtone_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Loading_Ringtone_Data_Thread loadingRingtoneDataThread = new Loading_Ringtone_Data_Thread();
                loadingRingtoneDataThread.start();
            }
        });

        order_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Loading_Order_Data_Thread loadingOrderDataThread = new Loading_Order_Data_Thread();
                loadingOrderDataThread.start();
            }
        });

        sign_out_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
                builder.setTitle("确定退出?");
                builder.setMessage("退出登录后将无法查看订单，重新登录后即可查看");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog1.dismiss();
                        set_dialog();

                        Upload_Sign_Out_Data_Thread uploadSignOutDataThread = new Upload_Sign_Out_Data_Thread();
                        uploadSignOutDataThread.start();
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                dialog1 = builder.create();
                dialog1.show();
            }
        });

        return root;
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
        LayoutInflater inflater1 = LayoutInflater.from(root.getContext());
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1: {
                Shop_Data_Thread shopDataThread = new Shop_Data_Thread();
                shopDataThread.start();
            }
        }
    }
}